package com.module.base.adapter.drag;


import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.module.base.base.adapter.BaseNewAdapter;

import java.util.Collections;

/**
 * Description :
 *
 * @author bsnl_yanxuwen
 * @date 2020/1/1311:02
 * 拖曳排序
 */
public abstract class DragAdapter<T> extends BaseNewAdapter<T> {
    public boolean isEdit;//是否是编辑状态

    /**
     * true 禁止拖曳
     */
    public abstract boolean isNotDragPosition(int position);

    /**
     * @return 长按时调用(开始拖曳的时候)
     */
    public abstract void onStarDrag(RecyclerView.ViewHolder viewHolder);

    /**
     * @return 松手时调用(停止拖曳)
     */
    public abstract void onEndDrag(RecyclerView.ViewHolder viewHolder);

    /**
     * 偏移量
     *
     * @param isCurrentlyActive 当前是否活动状态，也就是说false 就是松手。
     */
    public abstract void onEndOffset(RecyclerView.ViewHolder viewHolder, float mTouchX, float mTouchY, float dX, float dY, boolean isCurrentlyActive);


    public DragAdapter(RecyclerView recyclerView) {
        ItemDragCallback callback = new ItemDragCallback(this);
        ItemTouchHelper helper = new ItemTouchHelper(callback);
        helper.attachToRecyclerView(recyclerView);
        callback.setListener(new ItemDragCallback.Listener() {
            @Override
            public void onChildDrawOver(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
                onEndOffset(viewHolder, dX + viewHolder.itemView.getLeft(),
                    dY + viewHolder.itemView.getTop(),
                    dX, dY, isCurrentlyActive);
            }
        });
    }

    /**
     * 进入编辑状态
     */
    public void enterEdit() {
        isEdit = true;
        notifyItemRangeChanged();
    }

    public void closeEdit() {
        isEdit = false;
        notifyItemRangeChanged();
    }

    /**
     * 对拖拽的元素进行排序
     *
     * @param fromPosition
     * @param toPosition
     */
    void itemMove(int fromPosition, int toPosition) {
        if (fromPosition < toPosition) {
            for (int i = fromPosition; i < toPosition; i++) {
                Collections.swap(getData(), i - getHeaderLayoutCount(), (i + 1) - getHeaderLayoutCount());
            }
        } else {
            for (int i = fromPosition; i > toPosition; i--) {
                Collections.swap(getData(), i - getHeaderLayoutCount(), (i - 1) - getHeaderLayoutCount());
            }
        }
        notifyItemMoved(fromPosition, toPosition);
    }

    public int convert(int flags) {
        return 1 << flags;
    }

    public int addNotDrag(int AllFlags, int flags) {
        AllFlags |= convert(flags);
        return AllFlags;
    }

}
